package com.samp.base.jce.type02;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * AES对称加密，是用来替代原来的DES对称加密算法，更快，更安全，资源消耗更少。
 * 参考：https://blog.csdn.net/weixin_41205419/article/details/80311390
 * 另外，还有一种加密算法PBE(Password Base Encryption),这种没有密钥，基于口令加盐
 * https://blog.csdn.net/happylee6688/article/details/44650517
 */
public class AESDemo {

    private static String algorithm = "AES";

    private static String gengrateKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
        //AES要求密钥长度为128位,192位,256位
        keyGenerator.init(128);
        SecretKey secretKey = keyGenerator.generateKey();
        byte[] bytes = secretKey.getEncoded();
        return Base64.getEncoder().encodeToString(bytes);
//        return HexUtil.encodeHexStr(bytes);
    }

    public static String encrytMsg(String msg, String key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithm);
        SecretKey secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] result = cipher.doFinal(msg.getBytes());
        return Base64.getEncoder().encodeToString(result);
    }

    public static String decryptMsg(String encryptMsg, String key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithm);
        SecretKey secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), algorithm);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] result = cipher.doFinal(Base64.getDecoder().decode(encryptMsg));
        return new String(result);
    }

    public static void main(String[] args) {
        try {
            String key = gengrateKey();
            System.out.println("生成key:"+key);
            key = "eVKOxlzWaiWg2JnGl6YNrw==";
            String msg = "321245";
            String encryptMsg = encrytMsg(msg, key);
            System.out.println(msg+":加密后:"+encryptMsg);
            encryptMsg = "wimleyRFvAo7fddsrje07m3oCdtBFcQcPr6iuTjtQrc=";
            String decryptMsg = decryptMsg(encryptMsg, key);
            System.out.println(encryptMsg+":解密："+decryptMsg);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
